/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
/**
 * 分类界面
 * @type {*|exports|module.exports}
 */
var React = require('react');
var {
    StyleSheet,
    Text,
    View,
    TouchableHighlight,
    ListView,
    Image,
    BackAndroid,
    Platform,
    ScrollView,
    Animated,
    PixelRatio,
    Dimensions,
    Alert,
    Easing,
    Modal,
    TouchableOpacity,
    ActivityIndicator,
    AsyncStorage
} = require('react-native');

import Imagez from 'react-native-image-progress';
import NavTitle from '../component/NavTitle';
import Communications from '../utils/Communications';

import XFetch from '../XFetch';
import ContactServicer from './ContactServicer';

import ProductShops from './ProductShops';
import SearchBar from 'antd-mobile/lib/search-bar';

import Popup from 'antd-mobile/lib/popup';
import Grid from 'antd-mobile/lib/grid';

var ds;

import { connect } from 'react-redux';
import {changeAddress} from '../action/address';

import Toast from 'antd-mobile/lib/toast';
import Carousel from 'antd-mobile/lib/carousel';

import MyWebView from '../utils/MyWebView';

class Shops extends React.Component {
    // 构造函数
    constructor(props) {
        super(props);
        // 初始状态
        ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state =  {
            animating:false,
            dataLeftSource: ds.cloneWithRows([]),
            rightData:ds.cloneWithRows([]),
            sliderImage:[],//存放轮播图片
            show:false,
            text:'http://www.weiweigo.com/servelist.aspx?aid='+this.props.address.addressId
        };
    }
    componentDidMount() {
        this._changeAddress();
        XFetch(`http://www.weiweigo.com/app/content.aspx?method=getAddressAd&aid=${this.props.address.addressId}`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                sliderImage:data
            })
        });
        if(this.props.address.addressId == 0){
            this.props.change(2);
        }else{
            this._getGoods(this.props.address.addressId,null,null);
        }
    }

    componentWillReceiveProps(nextProps){
        if(nextProps.address.addressId == 0){
            nextProps.change(2);
        }else{
            this._getGoods(nextProps.address.addressId,null,null);
        }
    }

    _contactService(){
        this.props.navigator.push({
            name:'ContactServicer',
            component:ContactServicer
        })
    }

    _changeAddress(){
        this.setState({
            animating:true,
        })
        XFetch(`http://www.weiweigo.com/app/type.aspx?method=show&chnId=2&pid=0`,{
            method:'GET'
        }).then(data=>{
            this.setState({
                rightData:ds.cloneWithRows(data[1].childList),
                animating:false,
            })
        });
    }

    _getGoods(aid,cid,key){
        Toast.loading('数据加载中',30);
        let _p = '&';
        if(aid){
            _p+='aid='+aid+'&';
        }
        if(cid){
            _p+='cid='+cid+'&';
        }
        if(key){
            _p+='key='+key+'&';
        }
        XFetch(`http://www.weiweigo.com/app/shop.aspx?method=listByPage${_p}`,{
            method:'GET',
        }).then(data=>{
            Toast.hide();
            this.setState({
                dataLeftSource:ds.cloneWithRows(data.data),
                animating:false,
                text:'http://www.weiweigo.com/servelist.aspx?aid='+aid
            })
        });
    }

    _allShops(){
        this._getGoods(this.props.address.addressId,null,null);
    }

    _onRightClassify(data){
        this._getGoods(this.props.address.addressId,data.classId,null);
    }

    _onLeftSHop(data){
        this.props.navigator.push({
            name:'ProductShops',
            component:ProductShops,
            params:{
                id:data.shopId
            }
        })
    }

    _search(val){
        this._getGoods(this.props.id,null,val);
    }

    _joinUs(){
        this.props.navigator.push({
            component:MyWebView,
            name:'MyWebView',
            params:{
                path:'http://www.weiweigo.com/detail.aspx?id=939&aid='+this.props.address.addressId
            }
        })
    }

    _showSearch(){
        this.setState({
            show:!this.state.show
        });
    }

    _renderSlider(){
        return this.state.sliderImage.map((ele,index) =>{
            return (
                <TouchableOpacity
                    activeOpacity={1}
                    key={'ios'+index}
                    onPress={this._pressSlider.bind(this,ele)}
                    style={styles.slide}>
                    <Image source={{uri:`http://www.weiweigo.com${ele.src}`}} resizeMode="stretch" style={{height:120,width:Dimensions.get('window').width,justifyContent:'center',alignItems:'center'}}/>
                </TouchableOpacity>
            );
        });
    }

    _pressSlider(ele){
        this.props.navigator.push({
            component:MyWebView,
            name:'MyWebView',
            params:{
                path:ele.descride
            }
        })
    }

    render() {

        return (
            <View style={styles.wrap}>
                <NavTitle
                    title={'同城商家'+'-'+this.props.address.name}
                    headColor = '#fbdc3a'
                    leftButton = {true}
                    leftImg = {require('../imgs/left.png')}
                    leftText = "返回"
                    leftHander = {()=>{
                     //this.backTopLevel();
                      this.props.change(2);
                    }}
                    rightButton={true}
                    rightImg={require('../imgs/search.jpg')}
                    rightHander={this._showSearch.bind(this)}
                />
                {
                    this.state.show?
                        <SearchBar placeholder="搜索" onSubmit={this._search.bind(this)}/>
                    :null
                }
                <View style={{height:120}}>
                    {
                        this.state.sliderImage.length>0?
                            <Carousel
                                autoplay={true}
                                infinite={true}
                            >
                                {this._renderSlider()}
                            </Carousel>:
                            null
                    }

                </View>
                <View style={styles.container}>
                    <View style={styles.rightContent}>
                        <ListView
                            horizontal={false}
                            showsHorizontalScrollIndicator={false}
                            showsVerticalScrollIndicator = {false}
                            removeClippedSubviews = {true}
                            dataSource={this.state.dataLeftSource}
                            renderRow={this._renderLeftRowView.bind(this)}
                            enableEmptySections={true}
                            scrollRenderAheadDistance={5} />
                    </View>
                    <View style={styles.leftMenu}>
                        <ListView
                            horizontal={false}
                            showsHorizontalScrollIndicator={false}
                            showsVerticalScrollIndicator = {false}
                            removeClippedSubviews = {true}
                            dataSource={this.state.rightData}
                            renderRow={this._renderRightRowView.bind(this)}
                            enableEmptySections={true}
                            scrollRenderAheadDistance={5} />
                    </View>
                </View>
                <TouchableOpacity style={styles.shares} onPress={this._share.bind(this)}>
                    <Text>分享</Text>
                </TouchableOpacity>
            </View>
        );
    }

    _share(){
        Popup.show(
            <Grid hasLine={false} onClick={(ele,index)=>{
                    if(index === 0){
                        WechatAPI.shareToSession({
                            type: 'text',
                            text: this.state.text
                        })
                    }else if(index === 1){
                        WechatAPI.shareToTimeline({
                            type: 'text',
                            text: this.state.text
                        })
                    }else if(index === 2){
                        QQAPI.shareToQQ({
                            type: 'news',
                            title: '微微购',
                            description: '微微购服务详情分享',
                            webpageUrl: this.state.text,
                            imageUrl: 'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_DOtOgI4n.png',
                        });
                    }else{
                        QQAPI.shareToQzone({
                            type: 'news',
                            title: '微微购',
                            description: '微微购服务详情分享',
                            webpageUrl: this.state.text,
                            imageUrl: 'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_DOtOgI4n.png',
                        });
                    }
                    Popup.hide();
                }} data={[{
                    icon: require('../imgs/erweima2.png'),
                    text: `分享好友`,
                },{
                    icon: require('../imgs/erweima3.png'),
                    text: `分享朋友圈`,
                },{
                    icon: require('../imgs/erweima5.png'),
                    text: `分享QQ`,
                },{
                    icon: require('../imgs/erweima6.png'),
                    text: `分享空间`,
                }]} columnNum={3} renderItem={(ele,index)=>{
                    return (
                        <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                            <Image source={ele.icon} style={{width:42,height:42}}/>
                            <Text style={{marginTop:5}}>{ele.text}</Text>
                        </View>
                    )
                }}/>
            ,{animationType: 'slide-up',onMaskClose(){},maskClosable:true});
    }

    _renderRightRowView(rowData,sectionID,rowId) {
        return (
            <View>
                {
                    rowId == 0?
                        <View>
                    < TouchableOpacity onPress={this._allShops.bind(this)} style={{height: 32,justifyContent:'center',alignItems:'flex-start',paddingLeft:6,borderBottomWidth:1/PixelRatio.get(),borderColor:'#E0E0E0'}}>
                    <Text style={{fontSize:14,color:'#666',justifyContent:'center',alignItems:'center'}}>全部</Text>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this._joinUs.bind(this)} style={{height: 32,backgroundColor:'#f5cf10',justifyContent:'center',alignItems:'flex-start',paddingLeft:6,borderBottomWidth:1/PixelRatio.get(),borderColor:'#E0E0E0'}}>
                    <Text style={{fontSize:14,color:'#F00',justifyContent:'center',alignItems:'center'}}>同城客服</Text>
                    </TouchableOpacity>
                        </View>
                    :null
                }
            <TouchableHighlight
                style={{height: 32,justifyContent:'center',alignItems:'flex-start',paddingLeft:6,borderBottomWidth:1/PixelRatio.get(),borderColor:'#E0E0E0'}}
                underlayColor='#c8c7cc'
                onPress={this._onRightClassify.bind(this,rowData)}
            >
                <View style={{justifyContent:'center',alignItems:'center',flexDirection:'row'}}>
                    <Text numberOfLines={1} style={{fontSize:14,color:'#666',width:66,justifyContent:'center',alignItems:'center'}} >
                        {rowData.className}
                    </Text>
                </View>
            </TouchableHighlight>
            </View>
        );

    }
    _renderLeftRowView(rowData,sectionID,rowId) {
        return (
            <TouchableHighlight
                underlayColor='#c8c7cc'
                key={rowId}
                onPress={this._onLeftSHop.bind(this,rowData)}>
                <View style={styles.item}>
                    <Imagez
                        style={styles.userLogo}
                        resizeMode="stretch"
                        source={{uri:rowData.imgUrl?`http://www.weiweigo.com${rowData.imgUrl}`:'http://ouxiurkf8.bkt.clouddn.com/2017-08-21_CHyImm0T.png'}}
                        defaultSource={require('../imgs/default_image.png')}
                    />
                    <View style={styles.describe}>
                        <Text numberOfLines={1} style={styles.title} >
                            {rowData.title}
                        </Text>
                        <Text numberOfLines={2} style={styles.detail} >
                            {/\n/g.test(rowData.summary)?rowData.summary.replace(/\n/,''):rowData.summary}
                        </Text>
                    </View>
                    <TouchableOpacity
                        underlayColor='#c8c7cc'
                        style={styles.right}
                        onPress={() =>{
                            Communications.phoneCall(rowData.tel?rowData.tel:'10086',false)
                        }}
                    >
                        <Image source={require('../imgs/icPhoneSmallRed.png')} style={styles.phone}/>
                    </TouchableOpacity>
                </View>
            </TouchableHighlight>
        );
    }
    _onPress(rowData){

    }
};

var styles = {
    wrap: {
        flex: 1,
        backgroundColor: '#FFF',
    },
    container:{
        flex:1,
        flexDirection:'row',
        backgroundColor:'#F5F5F5',
    },
    topAd:{
        width:Dimensions.get('window').width,
        height:120
    },
    leftMenu:{
        backgroundColor:'#F0F0F0',
        width:70,
        borderColor:'#E0E0E0',
        borderRightWidth:1/PixelRatio.get()
    },
    rightContent:{
        flexDirection:'column',
        flex:2
    },
    item:{
        flexDirection:'row',
        padding:6,
        borderBottomWidth:1,
        borderColor:'#CCC'
    },
    userLogo:{
        width:40,
        height:40,
        borderRadius:3,
        alignSelf:'center'
    },
    describe:{
        flex:1,
        justifyContent:'flex-start',
        marginLeft:10,
        marginRight:5
    },
    title:{
        color:'#404040',
        fontSize:18
    },
    detail:{
        marginTop:6,
        color:'#999',
        fontSize:14,
        lineHeight:16
    },
    right:{
        width:20,
        justifyContent:'center',
        alignItems:'center',
        alignSelf:'center'
    },
    phone:{
        width:20,
        height:20
    },
    shares:{
        position:'absolute',
        top:Platform.OS === 'ios'?35:19,
        right:70,
        backgroundColor:'rgba(0,0,0,0)'
    }
};

const mapStateToProps = (state) => {
    return {
        address:state.address.address
    }
};

export default connect(
    mapStateToProps,{
        changeAddress
    }
)(Shops);
